package cn.tjad.tjad2.data.session;

import com.qiandian.android.base.common.bean.CommonBean;

import java.util.ArrayList;
import java.util.List;

import cn.tjad.tjad2.data.bean.CustomFormBean;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;

public class ProjectCustomForms {

    private volatile static ProjectCustomForms instance;
    private int projectId;
    private List<CustomFormBean> customFormList;

    private ProjectCustomForms() {}

    public static ProjectCustomForms getInstance() {
        if (instance == null) {
            synchronized (ProjectCustomForms.class) {
                if (instance == null) {
                    instance = new ProjectCustomForms();
                }
            }
        }
        return instance;
    }

    public void getCustomForms(OnProjectCustomFormListener listener) {
        if (Tools.getProjectId() == projectId) {
            if (customFormList != null) {
                notifyCaller(listener, customFormList);
            } else {
                requestProjectCustomForm(listener);
            }
        } else {
            requestProjectCustomForm(listener);
        }
    }

    private void requestProjectCustomForm(OnProjectCustomFormListener listener) {
        RetrofitManager.getInstance()
                .getApiService()
                .getCustomForms(Tools.getProjectId(), 0, 100)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<ArrayList<CustomFormBean>>(null) {
                    @Override
                    public void onSuccess(CommonBean<ArrayList<CustomFormBean>> t) {
                        projectId = Tools.getProjectId();
                        customFormList = t.result;
                        notifyCaller(listener, customFormList);
                    }

                    @Override
                    public void onFailed(String message) {

                    }
                });
    }

    private void notifyCaller(OnProjectCustomFormListener listener, List<CustomFormBean> customFormList) {
        if (listener != null) {
            listener.onProjectCustomFormGet(customFormList);
        }
    }

    public interface OnProjectCustomFormListener {
        void onProjectCustomFormGet(List<CustomFormBean> formList);
    }

}
